#!/usr/bin/env coffee

import {join, dirname} from 'path'
import {existsSync, readFileSync} from 'fs'
import DEV from '@/config/dev.js'
import PACKAGE_JSON from './package_json.coffee'
import {ver_int} from './ver.coffee'
import * as r64 from '../lib/r64.mjs'

do =>
  {dir} = process
  if not dir

    dir = __dirname

    if DEV
      dir = dirname dir

    process.dir = dir # 保证只有主进程会检测自动更新

    if DEV
      await import('@rmw/source-map-support/register')
    else
    #if 1 or not DEV

      {v} = (
        await import('./config.coffee')
      ).default
      if v
        if r64.decode(v) > ver_int(PACKAGE_JSON().version)
          {ROOT} = await import('./dir.coffee')
          now = join(ROOT,'v',v)
          entry = join(now,'m.js')
          if existsSync entry
            process.chdir now
            await import(entry)
            return
  await import('./ready.coffee')

  return
